package com.msb.mall.ware.service.impl;

import com.msb.common.constant.WareConstant;
import com.msb.mall.ware.entity.PurchaseDetailEntity;
import com.msb.mall.ware.service.PurchaseDetailService;
import com.msb.mall.ware.service.WareSkuService;
import com.msb.mall.ware.vo.MergeVO;
import com.msb.mall.ware.vo.PurchaseDoneVO;
import com.msb.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.ware.dao.PurchaseDao;
import com.msb.mall.ware.entity.PurchaseEntity;
import com.msb.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 查询采购单状态是新建或者已分配的采购单信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status", 0) // 新建状态
                .or().eq("status", 1); // 已分配状态

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    /**
     * 完成采购需求的合单操作
     *
     * @param mergeVO
     * @return
     */
    @Transactional
    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            // 新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
//            purchaseEntity.setStatus(0); // 设置状态为新建
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //判断采购单的状态 只能是新建或则已分配才能合单
        PurchaseEntity _purchaseEntity = this.getById(purchaseId);
        if (_purchaseEntity.getStatus() > WareConstant.PurchaseStatusEnum.RECEIVED.getCode()) {
            //不能合单
            return -1; // 返回-1表示合单失败

        }

        //整合采购需求单
        List<Long> items = mergeVO.getItems();
        final long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(e -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(e);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).filter(item -> {
            PurchaseDetailEntity entity = purchaseDetailService.getById(item.getId());
            if (entity.getStatus() == WareConstant.PurchaseDetailStatusEnum.CREATE.getCode() || entity.getStatus() == WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode()) {
                return true; // 只处理新建或已分配状态的采购需求
            } else {
                // 如果状态不是新建或已分配，则不处理
                return false;
            }
        }).collect(Collectors.toList());
        if (list != null && list.size() > 0) {
            purchaseDetailService.updateBatchById(list);
        }


        //更新对应的采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        return 1;
    }

    /**
     * 领取采购单
     *
     * @param ids
     */
    @Transactional
    @Override
    public void receive(List<Long> ids) {
        //1. 领取的采购单只能是新建状态或者已分配状态
        List<PurchaseEntity> list = ids.stream().map(e -> this.getById(e)).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode()); // 更新状态为已领取
            return item;
        }).collect(Collectors.toList());
        //2.  更新采购单状态为已领取
        this.updateBatchById(list);

        //3. 更新采购项的状态为正在采购
        for (Long id : ids) {
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailsByPurchaseId(id);
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode()); // 更新状态为正在采购
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }
    }


    @Transactional
    @Override
    public void done(PurchaseDoneVO vo) {
        Long purchaseId = vo.getId();


        //改变采购项的状态
        Boolean flag = true; // 用于标记采购状态 默认完成
        List<PurchaseItemDoneVO> items = vo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.HASEERROR.getCode()) {
                //该采购项出现问题
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {
                //采购项采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode()); // 更新状态为已完成
                //将采购成功的采购项进入库操作
                //根据采购项编号查询出对应的采购项详情
                PurchaseDetailEntity detailEntity1 = purchaseDetailService.getById(item.getItemId());

                //更新库存
                wareSkuService.addStock(detailEntity1.getSkuId(),
                        detailEntity1.getWareId(),
                        detailEntity1.getSkuNum());


            }
            detailEntity.setId(item.getItemId());
            purchaseDetailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);// 更新采购项状态

        //改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode() : WareConstant.PurchaseDetailStatusEnum.HASEERROR.getCode()); // 更新采购单状态
        this.updateById(purchaseEntity);


    }


}